package com.ofek.eventos;

import java.util.ArrayList;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.google.gson.Gson;
import com.ofek.applicationbase.broadcast.Delegate;
import com.ofek.applicationbase.utils.Log;
import com.ofek.eventos.EventsFragment.EventsFragmentController;
import com.ofek.eventos.db.EventosDatabaseService;
import com.ofek.eventos.db.EventosDatabaseService.EventosDatabaseServiceBinder;
import com.ofek.eventos.db.datatypes.EventData;
import com.ofek.eventos.db.datatypes.predefined.SearchScheme;

public class SearchActivity extends FragmentActivity implements ServiceConnection,EventsFragmentController {

	private static final int NUM_OF_PAGES = 3;
	public static final String INTENT_KEY_SEARCH_DEFAULTS = SearchActivity.class.getName()+".INTENT_KEY_SEARCH_DEFAULTS";
	public static final String INTENT_KEY_SEARCH_OPTION = SearchActivity.class.getName()+".KEY_SEARCH_OPTION";
	public final static int SEARCH_OPTION_SEARCH_EVENT = 0;
	public final static int SEARCH_OPTION_SEARCH_PEOPLE = 1;
	public final static int SEARCH_OPTION_SEARCH_RESULTS = 2;
	private static final String EVENTS_KEY = SearchActivity.class+".LastSearchResults";


	private ViewPager mPager;
	private SearchAdapter mPagerAdapter;
	private TextView header;
	private ImageView icon;
	private final int resDraws[] = new int[] {
			android.R.drawable.ic_menu_today,
			android.R.drawable.ic_menu_my_calendar,
			android.R.drawable.ic_menu_agenda
	};
	private final int resStrings[] = new int[] {
			R.string.search_events,
			R.string.search_people,
			R.string.search_results
	};




	public static class SearchResultsFragment extends EventsFragment {

	}


	private final SearchResultsFragment resultsFragment = new SearchResultsFragment();

	private final ToggleButton[] buttons = new ToggleButton[NUM_OF_PAGES];
	protected boolean shouldIgnoreCheck;
	public EventosDatabaseService eventosService;
	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		Log.d("onCreate");
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_search);

		final View title = findViewById(R.id.tool);
		header = (TextView)title.findViewById(R.id.header_text);
		final int i = getIntent().getIntExtra(INTENT_KEY_SEARCH_OPTION, SEARCH_OPTION_SEARCH_EVENT);
		icon = (ImageView)title.findViewById(R.id.icon);
		buttons[SEARCH_OPTION_SEARCH_EVENT] = (ToggleButton) title.findViewById(R.id.search_events);
		buttons[SEARCH_OPTION_SEARCH_PEOPLE] = (ToggleButton) title.findViewById(R.id.search_people);
		buttons[SEARCH_OPTION_SEARCH_RESULTS] = (ToggleButton) title.findViewById(R.id.results);
		choose(i);
		for (int  j = 0 ; j < NUM_OF_PAGES ; j++) {
			final int finalInt = j;
			buttons[j].setOnCheckedChangeListener(new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
					if (!shouldIgnoreCheck && isChecked) 
						mPager.setCurrentItem(finalInt,true);
				}
			});
		}
		mPager = (ViewPager) findViewById(R.id.view_flipper);
		mPagerAdapter = new SearchAdapter(getSupportFragmentManager());
		mPager.setAdapter(mPagerAdapter);
		mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
			@Override
			public void onPageSelected(final int i) {
				super.onPageSelected(i);
				header.setText(resStrings[i]);
				icon.setImageResource(resDraws[i]);
				choose(i);
				if (i==SEARCH_OPTION_SEARCH_RESULTS) 
					resultsFragment.setEventsToShow(events);
			}
		});
		header.setText(resStrings[i]);
		icon.setImageResource(resDraws[i]);
		mPager.setCurrentItem(i);
		if (savedInstanceState!=null)
			events=(ArrayList<EventData>) savedInstanceState.getSerializable(EVENTS_KEY);
		resultsFragment.setEventsToShow(events);
		resultsFragment.setEmptyStringRes(R.string.no_events_found);
		bindService(new Intent(this,EventosDatabaseService.class), this, 0);
	}
	public ArrayList<EventData> getLastSearchResults() {
		return events;
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unbindService(this);
	}
	private ArrayList<EventData> events;
	public void initiateSearch(final SearchScheme search) {
		resultsFragment.setWaitingState(true);
		eventosService.searchEvents(search,new Delegate<ArrayList<EventData>>() {

			@Override
			public void invoke(final ArrayList<EventData> t) {
				runOnUiThread(new Runnable() {



					@Override
					public void run() {
						events = t;
						resultsFragment.setEventsToShow(events);
					}
				});

			}
		});
		mPager.setCurrentItem(SEARCH_OPTION_SEARCH_RESULTS);
	}

	private void choose(final int i) {
		for (int  j = 0 ; j < NUM_OF_PAGES ; j++) {
			if (j==i) continue;
			buttons[j].setChecked(false);
			buttons[j].setEnabled(true);
		}
		shouldIgnoreCheck = true;
		buttons[i].setChecked(true);
		buttons[i].setEnabled(false);
		shouldIgnoreCheck =false;
		getIntent().putExtra(INTENT_KEY_SEARCH_OPTION, i);
	}

	@Override
	public boolean onCreateOptionsMenu(final Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.search, menu);
		return true;
	}



	public class SearchAdapter extends FragmentStatePagerAdapter {

		public SearchAdapter(final FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(final int position) {

			switch (position) {
			case SEARCH_OPTION_SEARCH_EVENT:
				final SearchEventsFragment searchEventsFragment = new SearchEventsFragment();
				final Bundle bundle = new Bundle();
				searchEventsFragment.setArguments(bundle);
				final SharedPreferences searchHistory = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
				final String lastSearch = searchHistory.getString(SEARCH_HISTORY, null);
				SearchScheme searchData = null;
				if ( lastSearch!=null ) 
					searchData=new Gson().fromJson(lastSearch, SearchScheme.class);
				if ( searchData!=null ) bundle.putSerializable(SearchDefinerFragment.INTENT_KEY_SEARCH_DEFAULTS, searchData);
				return searchEventsFragment;
			case SEARCH_OPTION_SEARCH_PEOPLE: 
				return new Fragment();
			case SEARCH_OPTION_SEARCH_RESULTS:
				return resultsFragment;
			}
			return null;
		}

		@Override
		public int getCount() {
			return NUM_OF_PAGES;
		}
	}


	private static final String SEARCH_HISTORY = "SEARCH_HISTORY";
	@Override
	public void onServiceConnected(final ComponentName arg0, final IBinder arg1) {
		Log.d("onServiceConnected");
		eventosService = ((EventosDatabaseServiceBinder)arg1).getEventosService();
	}

	@Override
	public void onServiceDisconnected(final ComponentName arg0) {
	}

	@Override
	protected void onSaveInstanceState(final Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putSerializable(EVENTS_KEY, events);
	}
	@Override
	public void onShowing(final Fragment frag) {
		if (events!=null) {
			((EventsFragment) frag).setEventsToShow(events);
			return;
		}
		final SharedPreferences searchHistory = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		final String lastSearch = searchHistory.getString(SEARCH_HISTORY, null);
		if ( lastSearch!=null ) 
			initiateSearch(new Gson().fromJson(lastSearch, SearchScheme.class));
	}
	@Override
	public void onEventPressed(final EventData event) {
		final Intent intent = new Intent(this, FormActivity.class);
		final Bundle bundle = new Bundle();
		intent.putExtras(bundle);
		startActivity(intent);
	}

	public static class SearchEventsFragment extends SearchDefinerFragment {


		@Override
		public void onFormSubmitted() {
			final SharedPreferences searchHistory = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
			searchHistory.edit().putString(SEARCH_HISTORY, new Gson().toJson(searchData)).commit();
			((SearchActivity)getActivity()).initiateSearch(searchData);
		}
	}

}
